package edu.kit.ksri.db.mturk.standaloneutils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

import edu.kit.ksri.db.mturk.var.StaticInformation;

/**
 * Copyright (c) 2010-2011 Karlsruhe Institute of Technology (KIT), Germany
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 * 
 * --------------------------------------------------------------------------
 * 
 * Software: CSP/WMV tool for dynamic quality management of microtasks
 * http://www.ksri.kit.edu/Upload/Users/PeopleClouds/HCOMP2011_An_extendable_toolkit_for_managing_quality_of_human-based_eServices.pdf
 * 
 * Organization: Karlsruhe Institute of Technology (KIT), Germany
 * http://www.kit.edu
 * 
 * Project: PeopleClouds project of the Karlsruhe Service Research Institute(KSRI)
 * http://www.ksri.kit.edu/Default.aspx?PageId=818
 * 
 * Contributing authors: David Bermbach, Sandra Rath, Pascal Wichmann, Robert Kern
 * 
 * ---------------------------------------------------------------------------
 * 
 * Purpose: This class converts CSV files into XML files in case the CSV are in a certain format
 */
public class ConverterCSV2XML {

	private static final Logger basiclog = Logger.getLogger("basic."
			+ ConverterCSV2XML.class);

	public static void main(String args[]) {

		String inputDirectory = "C:\\Hannes.csv";

		File csvFile = new File(inputDirectory);

		try {
			// Read all lines in the CSV file
			BufferedReader br = new BufferedReader(new FileReader(csvFile));
			String line = br.readLine();
			StringTokenizer st = null;
			
			int mappingNumber = 0;
			
			while ((line = br.readLine()) != null) {
				
				// Initialize tokenizer
				st = new StringTokenizer(line, ";");

				// Read HIT ID
				String hitid = st.nextToken();
				
				// Read number of results
				int number = Integer.parseInt(st.nextToken());

				// Prepare XML string
				String xml = "";

				// Do that for every assignment in the CSV file
				for (int i = 1; i <= number; i++) {
					System.out.println(i);
					
					// Read worker ID
					String workerid = st.nextToken();

					// Read assignment ID
					String assignmentID = st.nextToken();

					// Read submission time
					String submissionTime = st.nextToken();

					// Read the answer
					String answer = st.nextToken();
					
					// Log what we just read
					basiclog.info("Current HIT is " + hitid + " and assignment is " + assignmentID + ". Answer is " + answer);

					// Concatenate the XML answer
					xml = xml + "<Result worker=\"" + workerid + "\" assignmentID=\"" + assignmentID + "\" submissionTime=\"" + submissionTime + "\">"
							+ "<QuestionFormAnswers xmlns=\"http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionFormAnswers.xsd\"><Answer>"
							+ "<QuestionIdentifier>1</QuestionIdentifier><FreeText>" + answer + "</FreeText></Answer></QuestionFormAnswers>" + "</Result>";

					// Get new assignment
					if(i != number){
						line = br.readLine();
						if(line != null){
							st = new StringTokenizer(line, ";");
							// Discard HIT ID and number of results
							st.nextToken();
							st.nextToken();
						}
					}
				}
				
				xml = "<?xml version=\"1.0\"?><AllResults hitid=\""
						+ hitid + "\" mappingNumber=\"" + (mappingNumber+1) + "\" numberOfResults=\"" + number + "\">" + xml + "</AllResults>";
				
				mappingNumber++;
				
				// Write XML file
				File all = new File(
						StaticInformation.simMTurkOutputDirectory + "/all."
								+ hitid + ".xml");
				PrintWriter pw = new PrintWriter(all);
				pw.print(xml);
				pw.flush();
				pw.close();
			}
		} 
		catch (Exception e) {
			basiclog.error("Error while reading file " + csvFile);
		}

	}

}
